package com.jml.生产者消费者;


import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:jml
 * @date: 2019/5/5 17:50
 * @description：生产一个消费一个
 */
class MyResource<T> {

    private volatile boolean FLAG = true;//默认开启进行生产+消费
    private AtomicInteger atomicInteger = new AtomicInteger();
    BlockingQueue<T> blockingQueue = null;

    public MyResource(BlockingQueue<T> blockingQueue) {
        this.blockingQueue = blockingQueue;
    }

    public void myProduce() throws InterruptedException {
        String data = null;
        boolean retValue;
        while (FLAG) {
            data = atomicInteger.incrementAndGet() + "";
            retValue = blockingQueue.offer((T) data, 2L, TimeUnit.SECONDS);
            if (retValue) {
                System.out.println(Thread.currentThread().getName() + "\t" + "插入队列" + data + "成功");
            } else {
                System.out.println(Thread.currentThread().getName() + "\t" + "插入队列" + data + "失败");
            }
            Thread.sleep(1000);
        }
        System.out.println(Thread.currentThread().getName() + "\t 大老板叫停，表示FLAG=false，生产结束");
    }

    public void myConsumer() throws InterruptedException {
        T result;
        while (FLAG) {
            result = blockingQueue.poll(2L, TimeUnit.SECONDS);
            if (result != null) {
                System.out.println(Thread.currentThread().getName() + "\t" + "消费队列" + result + "成功");
            } else {
                FLAG = false;
                System.out.println(Thread.currentThread().getName() + "\t 2S没有获取数据，消费结束");
                return;
            }
        }
    }

    public void stop(){
        this.FLAG=false;
    }
}

public class 阻塞队列生产消费者 {

    public static void main(String[] args) throws InterruptedException {
        MyResource myResource = new MyResource(new ArrayBlockingQueue<>(10));
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t 生产线程启动");
            try {
                myResource.myProduce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Prod").start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t 消费线程启动");
            try {
                myResource.myConsumer();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "Consumer").start();

        Thread.sleep(5000);
        myResource.stop();
        System.out.println("时间到，main停止");
    }
}
